/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package tbquestion_client.form;

import bllobjects.Account;
import fsktms.request.IRequestDelegate;
import fsktms.request.Request;
import fsktms.request.RequestParameters;
import fsktms.request.RequestRespond;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.IOException;
import java.util.Collection;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFrame;
import model.ClientModel;
import qclient.QClient;

/**
 *
 * @author Mrkupi
 */
public class friendRequest extends javax.swing.JFrame {

    /**
     * Creates new form friendRequest
     */
    public friendRequest() {
        initComponents();
        setLocation( 400, 200 );
        
        setResizable(false);
        
        this.tbName.setModel(ClientModel.getInstance().getRequestsModel());
        this.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
        this.addWindowListener(new WindowAdapter(){
            @Override
            public void windowClosing(WindowEvent e){
                e.getWindow().setVisible(false);
            }
        });
        
        this.loadRequests();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        tbName = new javax.swing.JTable();
        jLabel1 = new javax.swing.JLabel();
        btAccept = new javax.swing.JButton();
        btDecline = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        tbName.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Name"
            }
        ));
        jScrollPane1.setViewportView(tbName);

        jLabel1.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
        jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabel1.setText("FRIEND REQUESTS");

        btAccept.setText("Accept");
        btAccept.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btAcceptActionPerformed(evt);
            }
        });

        btDecline.setText("Decline");
        btDecline.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btDeclineActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 375, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(129, 129, 129)
                        .addComponent(jLabel1))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(111, 111, 111)
                        .addComponent(btAccept)
                        .addGap(40, 40, 40)
                        .addComponent(btDecline)))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addGap(25, 25, 25)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 138, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btAccept)
                    .addComponent(btDecline))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btAcceptActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btAcceptActionPerformed
        int row     =   this.tbName.getSelectedRow();
        int colum   =   this.tbName.getSelectedColumn();
        if (row >= 0 && colum >= 0)
        {
            final String name =   (String)this.tbName.getValueAt(row, colum);
            try 
            {
                // insert new relationship
                RequestParameters params = new RequestParameters()
                        .set(RequestParameters.KEY_FUNCTION, "insertNewRelationShip")
                        .set("Name", name);
                final friendRequest thisCopy = this;
                QClient.getInstance().getRequestManager().sendRequest(
                        new Request("Relation", params, new IRequestDelegate() {

                    @Override
                    public void requestCompleted(RequestRespond respond) {
                        boolean isSuccess = respond.getBoolean(RequestParameters.KEY_RESULT);
                        if (isSuccess)
                        {
                            ClientModel.getInstance().getRequestsModel().removeRequest(name);
                            
                        }
                        else
                        {
                            //show failed
                        }
                    }
                }));

                // delete request
                params = new RequestParameters()
                        .set(RequestParameters.KEY_FUNCTION, "deleteRequestFriend")
                        .set("Name", name);
                QClient.getInstance().getRequestManager().sendRequest(
                        new Request("Relation", params, new IRequestDelegate() {

                    @Override
                    public void requestCompleted(RequestRespond respond) {
                        boolean isSuccess = respond.getBoolean(RequestParameters.KEY_RESULT);
                        if (isSuccess)
                        {
                            ClientModel.getInstance().getRequestsModel().removeRequest(name);
                            thisCopy.loadFriendAccount(name);
                        }
                        else
                        {
                            //show failed
                        }
                    }
                }));
            } catch (IOException ex) 
            {
                Logger.getLogger(friendRequest.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }//GEN-LAST:event_btAcceptActionPerformed

    private void btDeclineActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btDeclineActionPerformed
        int row     =   this.tbName.getSelectedRow();
        int colum   =   this.tbName.getSelectedColumn();
        if (row < 0 || colum < 0)
        {
            return;
        }
        
        final String name =   (String)this.tbName.getValueAt(row, colum);
        try 
        {
            RequestParameters params = new RequestParameters()
                    .set(RequestParameters.KEY_FUNCTION, "deleteRequestFriend")
                    .set("Name", name);
            QClient.getInstance().getRequestManager().sendRequest(
                    new Request("Relation", params, new IRequestDelegate() {

                @Override
                public void requestCompleted(RequestRespond respond) {
                    boolean isSuccess = respond.getBoolean(RequestParameters.KEY_RESULT);
                    if (isSuccess)
                    {
                        ClientModel.getInstance().getRequestsModel().removeRequest(name);
                    }
                    else
                    {
                        //show failed
                    }
                }
            }));
            
        } catch (IOException ex) 
        {
            Logger.getLogger(friendRequest.class.getName()).log(Level.SEVERE, null, ex);
        }
    }//GEN-LAST:event_btDeclineActionPerformed

    private void loadFriendAccount(String friendName)
    {try 
        {
            RequestParameters params = new RequestParameters()
                    .set(RequestParameters.KEY_FUNCTION, "getAccountInfo")
                    .set("ID", friendName);
            QClient.getInstance().getRequestManager().sendRequest(
                    new Request("Account", params, new IRequestDelegate() {

                @Override
                public void requestCompleted(RequestRespond respond) {
                    if (respond.isSuccess())
                    {
                        ClientModel.getInstance().getFriendList().addAccount((Account) respond.getResult());
                    }
                }
            }));
            
        } catch (IOException ex) 
        {
            Logger.getLogger(friendRequest.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btAccept;
    private javax.swing.JButton btDecline;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable tbName;
    // End of variables declaration//GEN-END:variables

    private void loadRequests() {
        try 
        {
            RequestParameters params = new RequestParameters()
                    .set(RequestParameters.KEY_FUNCTION, "getRequestedFriend")
                    .set("Name", ClientModel.getInstance().getAccount().getUserID());
            final friendRequest thisCopy = this;
            QClient.getInstance().getRequestManager().sendRequest(
                    new Request("Relation", params, new IRequestDelegate() {

                @Override
                public void requestCompleted(RequestRespond respond) {
                    if (respond.isSuccess())
                    {
                        ClientModel.getInstance().getFriendList().addAccounts((Collection<Account>)respond.getResult());
                    }
                }
            }));
        } 
        catch (IOException ex) {
            Logger.getLogger(ClientModel.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}
